<?php

namespace app\admin\controller\sample;

use app\common\controller\Backend;
use PHPExcel_IOFactory;

class Sample extends Backend
{

    protected $model = null;
    protected $searchFields = 'id,name,tel,school';
    public function _initialize()
    {
        $this->Teachermodel = new \app\admin\model\from\Teacher;
        $this->Familymodel = new \app\admin\model\from\Family;
        $this->Promotemodel = new \app\admin\model\from\Promote;
        $this->Sample_arr = Sample_arr();
        parent::_initialize();
       $this->view->assign("getReceiveList", $this->Teachermodel->getReceiveList());
       $this->view->assign("getGradeList", $this->Teachermodel->getGradeList());
       $this->view->assign("getGiftList", $this->Teachermodel->getGiftList());
       $this->view->assign("getMessageList", $this->Teachermodel->getMessageList());
  
    }

    /**
     * 查看
     */
    public function index()
    {
        //地区
        $this->assignconfig("arealist", $this->Familymodel->getProvinceOrderList());
        $this->assignconfig("userlist", $this->Familymodel->getuserName());
        return $this->view->fetch();
    }
    public function teacher_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->Teachermodel
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->Teachermodel
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            //print_R($this->Teachermodel->getLastSql());die;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }
    public function family_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->Familymodel
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->Familymodel
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function promote_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->Promotemodel
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->Promotemodel
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }
     /**
     * 发送短信
     */
    public function send(){
       if ($this->request->isPost()) {
      
        $type = $this->request->post('type');
        $status = $this->request->post('status');
        $params = $this->request->post('row/a');
        $book = $this->request->post('book/a');
        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $area = $this->request->post("area");
        if($province){
            $params['province'] = $province;
             if($city){
                $params['city'] = $city;
                if($area){
                  $params['area'] = $area;
                }
             }
        }else{
            $this->error("请选择地区");
        }
        if($params){

                $where = [];
                foreach ($params as $key => $value) {
                    if($value){
                        $where[$key] = $value;
                    }
                }
                $where['receive'] = 1;
                $model = model(GetTableModel($this->Sample_arr[$type]['model']));
                if($status == 2){
                    $data = $model->where($where)->where(function ($query) {
                            $query->where('message_status', '=', 1)->whereOr('message_status','=', 2);})->field('id,tel,message_status,message_num')->select()->toArray();
                }else{
                    $where['message_status'] = $status;
                    $data = $model->where($where)->field('id,tel,message_status,message_num')->select()->toArray();
                }
                if($data){
                    ignore_user_abort(true);
                    set_time_limit(0);
                    write_log([],'',2);
                    $info = send_message($type,$book,$data); 
                   // $info = send_ali_message($type,$book,$data); 
                    if(is_array($info)){
                        $this->success("共执行:".$info['count']."条，成功:".$info['ok_count']."条");
                    }else{
                        write_log([],'',3);
                        $this->success("执行失败");
                    }
                }else{
                    write_log([],'',3);
                    $this->error("数据为空");
                }
       
           
         }
        }
        return $this->view->fetch();
    }
     /**
     * 添加
     */
    public function teacher_add(){
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Teacher');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_teacher,tel',
                    ]);
                    $result = $this->Teachermodel->validate('Teacher.add')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->Teachermodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
     /**
     * 编辑
     */
    public function teacher_edit($ids = NULL)
    {
        $row = $this->Teachermodel->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Teacher');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_teacher,tel,' . $row->id,
                    ]);
                    
                    $result = $row ->validate('Teacher.edit')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function family_add(){
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Family');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_family,tel',
                    ]);
                    $result = $this->Familymodel->validate('Family.add')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->Familymodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function family_edit($ids = NULL)
    {
        $row = $this->Familymodel->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Family');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_family,tel,' . $row->id,
                    ]);
                    
                    $result = $row ->validate('Family.edit')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function promote_add(){
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $this->request->post("province");
            $params['city'] = $this->request->post("city");
            $params['area'] = $this->request->post("area");
            $params['teacher_school'] = $params['school'];
            $params['teacher_grade'] = $params['grade'];
            $params['teacher_address'] = $params['address'];
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Promote');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_promote,tel',
                    ]);
                    $result = $this->Promotemodel->validate('Promote.add')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->Promotemodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function promote_edit($ids = NULL)
    {
        $row = $this->Promotemodel->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['province'] = $params['teacher_provine'] = $this->request->post("province");
            $params['city'] = $params['teacher_city'] = $this->request->post("city");
            $params['area'] = $params['teacher_area'] = $this->request->post("area");
            $params['teacher_school'] = $params['school'];
            $params['teacher_grade'] = $params['grade'];
            $params['teacher_address'] = $params['address'];
            if ($params) {
                try {
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('Promote');
                   $adminValidate->rule([
                        'tel' => 'require|max:11|unique:from_promote,tel,' . $row->id,
                    ]);
                    
                    $result = $row ->validate('Promote.edit')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
     
     /**
     * 导入发送
     */
    public function send_excel($type = null,$ids = ""){
      if ($this->request->isPost()) {
            ignore_user_abort(true);
            set_time_limit(0);
            write_log([],'',2);
            $type = $this->request->post('type');
            $status = $this->request->post('status');
            $params = $this->request->post('row/a');
            $book = $this->request->post('book/a');
            $file = $params['import'];
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            $result = excelToArraySend($filePath,$book,$type,$status);
            if(!$result['status']){
                $info = $result['info'];
                if($info['no_url']){
                    $this->success("总共:".$info['count_total']."条，共发送:".$info['count']."条，成功:".$info['ok_count']."条",$info['no_url'],1);
                }
                $this->success("总共:".$info['count_total']."条，共发送:".$info['count']."条，成功:".$info['ok_count']."条");
            }
            write_log($result,'',3);
            $this->error($result['msg']);
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function delete($type = null,$ids = ""){
 
        if ($ids && $type ) {
            switch ($type) {
                case 1:
                    $this->model = $this->Teachermodel;
                    break;            
                 case 2:
                    $this->model = $this->Familymodel;
                    break;           
                 case 3:
                    $this->model = $this->Promotemodel;
                    break;
                default:
                    $this->error(__('Parameter %s can not be empty', 'type'));
                    break;
            }
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
     /**
     * 发送短信
     */
    public function send_one($type = null,$ids = ""){
     if(!$type||!$ids) $this->error(__('Parameter %s can not be empty', 'ids'));
     
        switch ($type) {
            case 1:
                $this->model = $this->Teachermodel;
                break;            
             case 2:
                $this->model = $this->Familymodel;
                break;           
             case 3:
                $this->model = $this->Promotemodel;
                break;
            default:
                $this->error(__('Parameter %s can not be empty', 'type'));
                break;
        }
        $pk = $this->model->getPk();
        $data = $this->model->where($pk, 'in', $ids)->field('id,tel,message_status,message_num')->select()->toArray();
        if (!$data)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            ignore_user_abort(true);
            set_time_limit(0);
            write_log([],'',2);
            $book = $this->request->post('book/a');
            $info = send_message($type,$book,$data); 
            //$info = send_ali_message($type,$book,$data); 
            if(is_array($info)){
                $this->success("共执行:".$info['count']."条，成功:".$info['ok_count']."条");
            }
            write_log([],'',3);
            $this->success("执行失败");
        }
        return $this->view->fetch();
    }
    

}
